window.onload = function() {
    var regionSelect = document.getElementById('region-select');
    var productSelect = document.getElementById('product-select');
    regionSelect.addEventListener('change', function() {
        console.log(regionSelect.value)
        console.log(getData(regionSelect.value, productSelect.value));
        showData();
    })
    productSelect.addEventListener('change', function() {
        showData();
    })
    let table = document.getElementById('table');
    showData();

    function showData() {
        clearData();
        let data = getData(regionSelect.value, productSelect.value);
        let tr = document.createElement('tr');
        let th = document.createElement('td');
        let th2 = document.createElement('td');
        th.innerHTML = '商品';
        th2.innerHTML = '地区';
        tr.appendChild(th);
        tr.appendChild(th2);
        table.appendChild(tr);
        for (let i = 1; i <= 12; i++) {
            let th = document.createElement('td');
            th.innerHTML = i + '月';
            tr.appendChild(th);
        }
        for (let i = 0; i < data.length; i++) {
            let tr = document.createElement('tr');
            let td1 = document.createElement('td');
            td1.innerHTML = data[i].product;
            tr.appendChild(td1);
            let td2 = document.createElement('td');
            td2.innerHTML = data[i].region;
            tr.appendChild(td2);
            for (let j = 0; j < data[i].sale.length; j++) {
                let td = document.createElement('td');
                td.innerHTML = data[i].sale[j];
                tr.appendChild(td);
            }
            table.appendChild(tr);
        }
    }

    function clearData() {
        while (table.hasChildNodes()) {
            table.removeChild(table.firstChild);
        }
    }

    function getData(region, product) {
        let result = [];
        for (let i = 0; i < sourceData.length; i++) {
            if (sourceData[i].region == region && sourceData[i].product == product) {
                result.push(sourceData[i]);
            }
        }
        return result;
    }
}